//
//  TicketHolderController.swift
//  ANOA
//
//  Created by 邱仙凯 on 2018/11/9.
//  Copyright © 2018 zwb. All rights reserved.
//

import UIKit
import BTNavigationDropdownMenu

struct filterParam {
    var startDate = ""
    var endDate = ""
    var minMoney = ""
    var maxMoney = ""
    var f_invoicetype_id = ""
    var liushui = ""
    var no = ""
    var biaoqian = ""
}


 
class TicketHolderController: OATableViewController,invoiceFilterable {
    
    
    
    
    lazy var orgBtn: UIButton = {
        let v = UIButton()
        v.backgroundColor = UIColor(kshex: "#DEEAFF")
        v.layer.cornerRadius = 15

        return v
    }()
    
    lazy var orgContentLab: UILabel = {
        let v = UILabel()
        v.text = "--"
        v.font = UIFont.boldSystemFont(ofSize: 16)

        v.textColor = Theme.primaryColor()

        v.isUserInteractionEnabled = false
        return v
    }()
    lazy var orgContentIcon: UIImageView = {
        let v = UIImageView()
        v.extImage(img: UIImage(named: "ticket_tri"))
        v.isUserInteractionEnabled = false
         return v
    }()
    
    lazy var countLab: UILabel = {
        let v = UILabel()
        return v
    }()
    lazy var moneyLab: UILabel = {
        let v = UILabel()
        return v
    }()
 
    lazy var headBg:UIView = {
        let v = UIView()
        return v
    }()
    lazy var comSearchBanner:ComSearch2V = {
        let v = ComSearch2V()
        return v
    }()
    var thodVM = TicketHolderVM()
    var checkTool = TicketCheckVC()
    var dropMenu:GHDropMenu?
    var startSelect = false // 可以选择的状态
    lazy var ccV:ChooseAndCheckView = {
        let ccV = ChooseAndCheckView(frame: CGRect(x: -KSGlobal.screenW ,y:KSGlobal.screenH - 120 ,width:KSGlobal.screenW,height:60))
        return ccV
    }()
    lazy var backItem:UIBarButtonItem = { // 返回
        let btn = UIButton.creat4Item(image: UIImage(named: "nav_com_back")) { btn in
            self.back()
        }
        btn.frame = CGRect(origin: .zero, size: CGSizeMake(26, 26))
        
        // 创建一个容器视图
              let containerView = UIView(frame: btn.bounds)
              containerView.addSubview(btn)
          let backItem = UIBarButtonItem(customView: containerView)
         return backItem
    }()
 
    var checkBtn:CheckButton = {
        var v = CheckButton()
        v.setTitle("批量查验", for: .normal)
        v.backgroundColor = .white
        v.layer.cornerRadius = 9
        v.setTitleColor(UIColor(kshex: "#2A304A"), for: .normal)
        v.setImage(UIImage(named: "check_check"), for: .normal)
        return v
    }()
    
    var zoneSegV:ZoneSegView = {
       let v = ZoneSegView()
        v.backgroundColor = .clear
        v.isUserInteractionEnabled = true
        v.blockWidthMultipliedBy = 0.7
         v.setCollecDataSource(arr: [SegmenttData(id: "", nm: "未报销"),SegmenttData(id: "", nm: "报销中"),SegmenttData(id: "", nm: "已报销")])
        return v
    }()
    // 覆盖父类方法，不让他回来刷新
    override func viewWillAppear(_ animated: Bool) {
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        menuView?.hide()
    }
    var menuView : BTNavigationDropdownMenu?
    override func viewDidLoad() {
        super.viewDidLoad()
        checkTool.vc = self
         typeDicDesc = InvoiceType.invoiceCode2Name.swapKeyValues()
        
        
         menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: BTTitle.index(0), items: TicketAppear.shared.invoiceCoType)
        
        menuView?.menuTitleColor =  .black
        menuView?.arrowTintColor =   .black
       
       
        menuView?.cellBackgroundColor = .white
        menuView?.cellTextLabelColor = .darkGray
        menuView?.cellSeparatorColor = .darkGray
        self.navigationItem.titleView = menuView
        menuView?.didSelectItemAtIndexHandler = { [unowned self] index in
            self.setOrgUserinterface(i: index)
            self.setOrg()
            if index == 2 {
                self.thodVM.fCompany = 1
                self.thodVM.invoiceTypeCode = "1"
            } else {
                self.thodVM.fCompany = index
                self.thodVM.invoiceTypeCode = "0"
            }
            
            self.tableView.mj_header?.beginRefreshing()
        }
        
        self.tableView.tableFooterView = UIView()
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = InvoiceHeight
        tableView.register(TicketSummaryCell.self, forCellReuseIdentifier: TicketSummaryCell.identifier)
        
     
        
      configHead()
        
        self.configOrgSelect()
        self.setOrgUserinterface(i: 0)
        
        self.configRightBarItem()
 
        self.tableView.mj_header?.beginRefreshing()
        
        self.tableView.addSubview(ccV)
        ccV.checkInvoiceClosure = { sender in
            if sender.tag == 1 { // 全选事件
                sender.isSelected = !sender.isSelected
                
                self.thodVM.dataArray = self.thodVM.dataArray.compactMap { (one) -> TicketModel in
                    var onev = one
                     if onev.selectable {
                           onev.isselected = sender.isSelected ? 1 : 0
                       } else {
                           onev.isselected = 0
                       }
                    return onev
                }

                self.tableView.reloadData()
                
            } else { // 开始查验事件
                let selArray =  self.thodVM.dataArray.filter{ $0.isselected == 1 }
                guard selArray.count > 0 else {
                    KSToast("未选择发票")
                    return
                }
                
                alertUtil(self, title: "确认校验这\(selArray.count)张发票", operateS: [nameAction(name: "确定", action: { [unowned self] (_) in
                    
                    if selArray.count == 1 { // 单张查验
                        var api:API!
                        if TicketAppear.shared.checkType == .typev4 {
                            api = API.invoice(.checkInvoiceV4(qrcode: jointURLString(selArray[0]),f_type: "2",id_key:selArray[0].idKey.unwrap,invoiceTypeCode: "\(self.thodVM.invoiceTypeCode)",f_buyername:selArray[0].fBuyername.unwrap,f_org_id: self.thodVM.idAname!.id))
                        } else {
                            api = API.invoice(.checkInvoiceV1(qrcode: jointURLString(selArray[0]),f_type: "2",id_key:selArray[0].idKey.unwrap,invoiceTypeCode: "\(self.thodVM.invoiceTypeCode)",f_buyername:selArray[0].fBuyername.unwrap,f_org_id: self.thodVM.idAname!.id))
                        }
                        
                        KSNetwork.shared.doRequest(api,showHud: true) { [weak self]  (data:BaseResult<OperateResult>) in
                            guard let `self` = self else {return}
                            self.tableView.mj_header?.beginRefreshing()
                            self.change2Checking(false)
                            KSToast(data.errorCombine.unwrap)
                        }
                        
                    } else { // 多张查验
                        var api:API!
                        if TicketAppear.shared.checkType == .typev4 {
                            api = API.invoice(.checkInvoiceMulitiV4(checkInvoices: models2json(selArray),invoiceTypeCode: "\(self.thodVM.invoiceTypeCode)",f_org_id: self.thodVM.idAname!.id))
                        } else {
                            api = API.invoice(.checkInvoiceMulitiV1(checkInvoices: models2json(selArray),invoiceTypeCode: "\(self.thodVM.invoiceTypeCode)",f_org_id: self.thodVM.idAname!.id))
                        }
                        
                         KSNetwork.shared.doRequest(api) { (data:BaseResult<OperateResult>) in
                            KSToast(data.errorCombine.unwrap)
                            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                                self.tableView.mj_header?.beginRefreshing()
                                self.change2Checking(false)
                            }
                        }
                    }
                    
                    
                })])
                
            }
            
        }
        self.tableView.bringSubviewToFront(ccV)
        configFilter()
    }
    
    
    func configFilter() {
         
       
       

        var t1 = inputTypeFilter(nm: "标签", param: "biaoqian")
        var t2 = inputTypeFilter(nm: "流水号", param: "liushui")
        var t3 = inputTypeFilter(nm: "发票号码", param: "no")
        var t4 = inputTypeFilter(nm: "最小金额", param: "MinMoney")
        var t5 = inputTypeFilter(nm: "最大金额", param: "MaxMoney")

        var t6 = TemplateModel(JSON:["":""])!
        t6.isFormSHow = "1"
        t6.isFilterShow = "1"
        t6.field_nm = "begin_dt"
        t6.field_annotation = "开始日期"
        t6.date_default_value = "5"
        t6.field_type = TemplateType.date.rawValue
      
    
        var t7 = TemplateModel(JSON:["":""])!
        t7.isFormSHow = "1"
        t7.isFilterShow = "1"
        t7.field_nm = "end_dt"
        t7.field_annotation = "结束日期"
        t7.date_default_value = "1"
        t7.field_type = TemplateType.date.rawValue
        
        
        var t8 = TemplateModel(JSON:["":""])!
        t8.isFormSHow = "1"
        t8.isFilterShow = "1"
        t8.field_nm = "f_invoicetype_nm"
        t8.field_annotation = "发票类型"
        t8.field_type = TemplateType.localSelect.rawValue
        var sDStr = ""
        let inArr = invoiceNameArr()
        for i in 0..<inArr.count {
            let item = inArr[i]
            let code = InvoiceType.name2code(item)
            if i == (inArr.count - 1) {
                sDStr += "\(code):\(item)"
            } else {
                sDStr += "\(code):\(item),"
            }
            
        }
      
        t8.select_data = sDStr
        t8.selectDataBack = LocalSelectDataBack(idBack: "f_invoicetype_id",nmBack: "f_invoicetype_nm")
        var t81 = TemplateModel(JSON:["":""])!
        t81.isFormSHow = "0"
        t81.isFilterShow = "0"
        t81.field_nm = "f_invoicetype_id"
        t81.field_type = TemplateType.input.rawValue
        

        let temf = [t6,t7,t8,t81,t1,t2,t3,t4,t5]
        
   
  
        let yyy = getTopH() + comSearchBanner.ks_height + zoneSegVHeight
       
        self.comSearchBanner.initWithFcontent(startY:yyy,templateFilter: temf)
        self.comSearchBanner.bannerComfirmClo = {
            if let isrefresh = self.tableView.mj_header?.isRefreshing,isrefresh {
                self.tableView.mj_header?.endRefreshing()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                    self.tableView.mj_header?.beginRefreshing()
                }
            }  else {
                self.tableView.mj_header?.beginRefreshing()
            }
        }
   
    }
    func configHead() {
      
                    headBg.addSubview(comSearchBanner)
            comSearchBanner.snp.makeConstraints { make in
                        make.left.right.top.equalToSuperview()
                        make.height.equalTo(40)
                    }
         

        let orangeV = UIImageView(image: UIImage(named: "piaojia_bg"))
        orangeV.isUserInteractionEnabled = true
        headBg.addSubview(orangeV)
        orangeV.snp.makeConstraints { make in
            make.left.equalTo(10)
            
           
                make.top.equalTo(comSearchBanner.snp.bottom).offset(5)
          
      
            
            make.right.equalTo(-10)
            make.height.equalTo(145)
        }
        orangeV.addSubview(orgBtn)
        orgBtn.addSubview(orgContentLab)
        orgBtn.addSubview(orgContentIcon)

        orgBtn.snp.makeConstraints { make in
             make.centerX.equalToSuperview()
            make.bottom.equalTo(-6)
            make.height.equalTo(30)
    
        }
     
        orgContentLab.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
             make.centerX.equalToSuperview().offset(-15)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-30)
        }
        orgContentIcon.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.width.equalTo(12)
            make.height.equalTo(12)
             make.left.equalTo(orgContentLab.snp.right).offset(6)
        }
        
        
        let line = UIView()
        line.backgroundColor = UIColor(kshex: "#CACEE1")
        orangeV.addSubview(line)
        line.snp.makeConstraints { make in
            make.width.equalTo(1)
            make.height.equalTo(49)
            make.centerX.equalToSuperview().offset(-30)
            make.top.equalToSuperview().offset(33)
        }
        
        let left1 = UILabel()
        left1.text = "累计张数(张)"
        left1.font = UIFont.systemFont(ofSize: 13)
        left1.textColor = UIColor(kshex: "#8991B0")
        orangeV.addSubview(left1)
        left1.snp.makeConstraints { make in
            make.right.equalTo(line).offset(-10)
            make.bottom.equalTo(line)
            make.width.equalTo(100)
        }
         countLab.textColor = UIColor(kshex: "#2A304A")
        countLab.font = UIFont.systemFont(ofSize: 24)
        orangeV.addSubview(countLab)
        countLab.snp.makeConstraints { make in
            make.right.equalTo(line).offset(-10)
            make.top.equalTo(line)
            make.width.equalTo(100)
        }
        let right1 = UILabel()
        right1.text = "累计金额(￥)"
        right1.font = UIFont.systemFont(ofSize: 13)

        right1.textColor = UIColor(kshex: "#8991B0")
        orangeV.addSubview(right1)
        moneyLab.textColor = UIColor(kshex: "#2A304A")
        orangeV.addSubview(moneyLab)
        moneyLab.font = UIFont.systemFont(ofSize: 24)
        
        right1.snp.makeConstraints { make in
            make.left.equalTo(line).offset(20)
            make.bottom.equalTo(line)
            make.width.equalTo(100)
        }
    
       

        moneyLab.snp.makeConstraints { make in
            make.left.equalTo(right1)
            make.top.equalTo(line)
        }
        
        headBg.addSubview(zoneSegV)
        zoneSegV.collecSelected = { indx ,data  in
            
            self.checkBtn.isHidden = indx > 0
            
            self.thodVM.status = data.nm.unwrap
            self.tableView.mj_header?.beginRefreshing()
        }
        zoneSegV.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(7)
            make.height.equalTo(36)
            make.width.equalTo(253)
        }
        headBg.addSubview(checkBtn)
        checkBtn.addTouchUpInSideAction { btnn in
            if btnn.titleLabel?.text == "批量查验" {
                self.change2Checking(true)
            } else {
                self.change2Checking(false)
            }
           
            
            
            
            self.tableView.reloadData()
            
        }
        checkBtn.snp.makeConstraints { make in
            make.height.equalTo(32)
            make.width.equalTo(100)
            make.centerY.equalTo(zoneSegV)
            make.right.equalToSuperview().offset(-7)
        }
        headBg.backgroundColor = Theme.commonBg
        
  
            headBg.frame = CGRect(x:0, y:0, width:KSGlobal.screenW, height:245)
      
        
        
        self.tableView.tableHeaderView = headBg
    }
    
    func change2Checking(_ ing:Bool) {
        if ing {
            self.checkBtn.setTitle("取消", for: .normal)
            self.checkBtn.setImage(UIImage(named: "check_cancel"), for: .normal)
            self.itemAndCheckViewStatus("取消", checkViewShow: true)
        } else {
            self.checkBtn.setTitle("批量查验", for: .normal)
            self.checkBtn.setImage(UIImage(named: "check_check"), for: .normal)
            self.itemAndCheckViewStatus("批量查验", checkViewShow: false)
        }
    }
    
    func delegateSearchAction() {
        configRightBarItem()
        self.tableView.mj_header?.beginRefreshing()
        
    }
    
    func configRightBarItem() {
        if filterPa.isNone {
            filterPa = filterParam()
        }
        var namestr:String = ""
        if filterPa!.startDate == "" &&
            filterPa!.endDate == ""  &&
            filterPa!.minMoney == ""  &&
            filterPa!.maxMoney == "" &&
            filterPa!.f_invoicetype_id == ""  &&
            filterPa!.liushui == ""  &&
            filterPa!.no == "" &&
            filterPa!.biaoqian == "" {
            namestr = "filterIcon"
        } else {
            namestr = "filterIcon_s"
        }
        let searchItem = UIBarButtonItem(image: UIImage(named:namestr)!.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(searchAction))
        let addItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction))
      
        addItem.tintColor = .black
       
        navigationItem.rightBarButtonItems = [addItem]
    }
    
    
    
    func setOrgUserinterface(i:Int) {
         // 0 不可选  1 可以选  2 销售票夹可以选   4-25号 改为都可以选
        self.orgBtn.isUserInteractionEnabled =  true
    }
    
    func setOrg(idname:idAndName = idAndName(name: USERINFO.cUnitnameHs.unwrap, id: USERINFO.cUnitnameIdHs.unwrap)) {
        self.thodVM.idAname = idname
        self.orgContentLab.text = "\(self.thodVM.idAname!.name)"
    }
    
    func configOrgSelect() {
        setOrg()
        orgBtn.addTouchUpInSideAction { _ in
            
            
           KSOrgSelectUtil.initWithNav(type: .single,backClosure: { node in
 
            self.setOrg(idname: idAndName(name: node.first!.name.unwrap, id: node.first!.id.unwrap))
            self.tableView.mj_header?.beginRefreshing()

              
            }){ vc in
                let topViewController = RouterUtils.currentTopViewController()
                topViewController!.present_FullScreen(to: vc)
            }
            
 
        }
        
    }
    
    
    // MARK: - Public Method
    override func fetchData(_ page: Int = 1) {
        itemAndCheckViewStatus("批量查验", checkViewShow: false)
        
        filterPa!.biaoqian = comSearchBanner.filterV!.filterDic["biaoqian"].unwrap
        filterPa!.liushui = comSearchBanner.filterV!.filterDic["liushui"].unwrap
        filterPa!.no = comSearchBanner.filterV!.filterDic["no"].unwrap
        filterPa!.minMoney = comSearchBanner.filterV!.filterDic["MinMoney"].unwrap
        filterPa!.maxMoney = comSearchBanner.filterV!.filterDic["MaxMoney"].unwrap
        filterPa!.startDate = comSearchBanner.filterV!.filterDic["begin_dt"].unwrap
        filterPa!.endDate = comSearchBanner.filterV!.filterDic["end_dt"].unwrap
        filterPa!.f_invoicetype_id = comSearchBanner.filterV!.filterDic["f_invoicetype_id"].unwrap

        
        let orgstr = (thodVM.fCompany == 1) ? self.thodVM.idAname!.id : ""
        KSNetwork.shared.doRequest4Sj(API.invoice(.queryInvoiceList(f_owner_id: "", page: "\(page)", count: "\(KSGlobal.pageSize)", begin_date: filterPa!.startDate, end_date: filterPa!.endDate, f_use_state:thodVM.status, f_company: "\(thodVM.fCompany)", invoiceTypeCode: "\(thodVM.invoiceTypeCode)",f_org_id:orgstr, begin_money: filterPa!.minMoney, end_money: filterPa!.maxMoney, f_recordnum: filterPa!.liushui, f_invoiceno: filterPa!.no, f_invoicetype_id: filterPa!.f_invoicetype_id,f_label:filterPa!.biaoqian)),showHud: false) { [weak self] (data:SwResult<TicketModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infos {
                  
                    
                    if self.page == 1 {
                        self.thodVM.dataArray.removeAll()
                        self.tableView.reloadData()
                    }
                    
                    if  infos.count < KSGlobal.pageSize {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                    infos.forEach {
                        var one = $0
                        if self.thodVM.status == "报销中" || self.thodVM.status == "已报销" {
                            one.withSource = true
                        } else {
                            one.withSelect = true
                        }
                        self.thodVM.dataArray.append(one)
                    }
                    
                    
                    self.page += 1
                    self.tableView.reloadData()
                    let countResult = self.thodVM.countSumInformation(self.thodVM.dataArray)
                    self.countLab.text = countResult.0
                    self.moneyLab.text = countResult.1
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
    }
   
 
    @objc func addAction() {
        var acArr = [nameAction]()
        
        if TicketAppear.shared.multiPDFAdd  {
            acArr += [nameAction(name: "批量选择PDF", action: { [unowned self] (_) in
                checkTool.choosePDF()
            })]
        }
        acArr += [nameAction(name: "扫描发票二维码", action: { [unowned self] (_) in
            checkTool.startScan()
            
        }),nameAction(name: "智能识别(相册)", action: { [unowned self] (_) in
            checkTool.startLibrary4Interlligent()
        
            }),nameAction(name: "智能识别(拍照)", action: { [unowned self] (_) in
                
                checkTool.startTakePhoto4Intelligent()
           
             }),nameAction(name: "手动新增(相册)", action: { [unowned self] (_) in
                checkTool.startDirectLibrary()
            }),nameAction(name: "手动新增(拍照)", action: { [unowned self] (_) in
                checkTool.startDirectTakePhoto()
            })]
        
        alertUtil(self, title: "选择",message: "温馨提示：刚开的发票查验一般会提示查无此票，是因为税务局还没同步发票信息，可以过3个小时左右再来录入",aStyle: .actionSheet, operateS: acArr)
        
        
    }
    @objc func searchAction() {
        if dropMenu.isNone {
            dropMenu = getDropMenu()
        }
        dropMenu!.show()
        
    }
    @objc func checkStartAction(sender:UIBarButtonItem) {
        if sender.title == "批量查验" {
            itemAndCheckViewStatus("取消", checkViewShow: true)
        } else {
            itemAndCheckViewStatus("批量查验", checkViewShow: false)
        }
        
        
        
        self.tableView.reloadData()
    }
    
 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return thodVM.dataArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: TicketSummaryCell.identifier, for: indexPath) as? TicketSummaryCell else {
            fatalError()
            }
        thodVM.dataArray[indexPath.row].startSelect = self.startSelect
        thodVM.dataArray[indexPath.row].selectable = (ifNeedCheck(one: thodVM.dataArray[indexPath.row]) && thodVM.dataArray[indexPath.row].fCheckstate.unwrap != "1")
        cell.one = thodVM.dataArray[indexPath.row]
        cell.selectionStyle = .none
        if thodVM.dataArray[indexPath.row].withSelect == true {
            cell.selBtn.tag = indexPath.row
            cell.selBtn.addTarget(self, action: #selector(self.invoiceSelectAction(sender:)), for: .touchUpInside)
        }
        cell.btnCheckStatus.addTouchUpInSideAction { [indexPath]  _ in
            if let checkinfo = self.thodVM.dataArray[indexPath.row].sCheckInfo,checkinfo != "" {
                KSToast(checkinfo)
            }
        }
        cell.deleteBtn.addTouchUpInSideAction { [indexPath] _  in
            self.deleteAction(idx: indexPath)
        }
        
        return cell
    }
    
    
    @objc func invoiceSelectAction(sender:UIButton) {
        
        thodVM.dataArray[sender.tag].isselected = (thodVM.dataArray[sender.tag].isselected == 1 ? 0 : 1)
        
        checkAllBtnStatus()
        self.tableView.reloadData()
        
        
    }
    // 全选的控制
    func checkAllBtnStatus() {
        var flag = true
        let availableA = thodVM.dataArray.filter { $0.selectable }
        for item in availableA {
            if item.isselected == 0 {
                flag = false
                break
            }
        }
        self.ccV.btn1.isSelected = flag
    }
    
    // MARK: - tableview 代理
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let one = thodVM.dataArray[indexPath.row]
        let vc = TicketContentController.initForIdkey(invoiceTypeCode: "\(self.thodVM.invoiceTypeCode)", id_key: one.idKey.unwrap, title: "修改发票") {
            self.tableView.mj_header?.beginRefreshing()
        }
        navigationController?.pushViewController(vc, animated: true)
        
        
    }
  
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if thodVM.status == "未报销" { // 只有没报销的可以删除
            return true
        } else {
            return false
        }
    }
    //返回编辑类型，滑动删除
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return UITableViewCell.EditingStyle.delete
    }
    
    //点击删除按钮的响应方法，在这里处理删除的逻辑
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {

            deleteAction(idx: indexPath)
 
        }
    }
    func deleteAction(idx:IndexPath) {
        let one = thodVM.dataArray[idx.row]
        
         KSNetwork.shared.doRequest(API.invoice(.deleteInvoice(id_key: one.idKey.unwrap,invoiceTypeCode: "\(self.thodVM.invoiceTypeCode)")),doubleCheck: DoubleCheckParam(controller: self, alertTitle: "确认删除？")) { [weak self] (data:BaseResult<OperateResult>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                self.thodVM.dataArray.remove(at: idx.row)
                 self.tableView.deleteRows(at: [idx], with: UITableView.RowAnimation.fade)
                let countResult = self.thodVM.countSumInformation(self.thodVM.dataArray)
                         self.countLab.text = countResult.0
                         self.moneyLab.text = countResult.1
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    // MARK: - scrollview 代理
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var frame = self.ccV.frame
        frame.origin.y = scrollView.contentOffset.y + self.tableView.frame.size.height - self.ccV.frame.size.height
        self.ccV.frame = frame
        self.view.bringSubviewToFront(self.ccV)
    }
    
}


extension TicketHolderController {
 
    // checkItem标题的处理， 底部view 上升和下降处理
    func itemAndCheckViewStatus(_ checkTitle:String, checkViewShow:Bool) {
        if checkViewShow {
            self.startSelect = true
            UIView.animate(withDuration: 0.2) {
                self.ccV.ks_x = 0
            }
        } else {
            self.startSelect = false
            self.ccV.btn1.isSelected = false
            UIView.animate(withDuration: 0.2) {
                self.ccV.ks_x = -KSGlobal.screenW
            }
        }
        
    }
    
    
    @objc func back() {
        self.navigationController?.popViewController(animated: true)
    }
    
}
class CheckButton:UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        self.titleLabel?.textAlignment = .center

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let width:CGFloat = 18
        self.imageView?.frame = CGRect(x: self.ks_width - 26, y: (self.ks_height - width)/2, width: width, height: width)
        self.titleLabel?.frame = CGRect(x: 5, y: 0, width: self.ks_width - 33, height: self.ks_height)

    }
}
